import { useLocation } from "react-router-dom";
import { useEffect, useState, useRef } from "react";
import to from "await-to-js";
import {
  getPlayAuth as getPlayAuthApi,
  getCommentList as getCommentListApi,
  comment as commentApi,
  getChildCommentList as getChildCommentListApi,
  like as likeApi,
  choseCollection as choseCollectionApi,
  getRelatedList as getRelatedListApi,
  handleCancelChose as handleCancelChoseApi,
  getVideoDetail as getVideoDetailApi,
  heartBeat as heartBeatApi,
} from "@/api/playPage";
import { WebsiteVideoVo } from "@/views/home/types";
import { CommentListBO } from "@/api/playPage/types";
import { useDispatch, useSelector } from "react-redux";

import { getCollectList as getCollectListApi } from "@/api/personal/index";
import { useNavigate } from "react-router-dom";
import type { PaginationProps } from "antd";
import {
  Flex,
  Typography,
  Tag,
  Button,
  Avatar,
  Space,
  Input,
  Tooltip,
  message,
  Pagination,
  Modal,
  Table,
} from "antd";
import {
  YoutubeFilled,
  MessageFilled,
  ExclamationOutlined,
  HeartOutlined,
  StarOutlined,
  UserOutlined,
  EditOutlined,
  PlusOutlined,
  DislikeOutlined,
  LikeOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";

const { Paragraph, Text } = Typography;

const Index: React.FC = () => {
  // 获取用户数据
  const { userInfo } = useSelector((state) => (state as any).user);
  // 获取路由传参
  const { state } = useLocation();
  // 控制视频描述展开
  const [ellipsis, setEllipsis] = useState(true);
  // 视频详情
  const [videoInfo, setVideoInfo] = useState(state.videoInfo);
  // 点赞数
  const [supportCount, setSupportCount] = useState(videoInfo.supportCount);
  // 评论数量
  const [collectCount, setCollectCount] = useState(videoInfo.collectionCount);
  // 热门视频列表
  const [hotVideoList, setHotVideoList] = useState<WebsiteVideoVo[]>([]);
  const videoPlayer = useRef("");
  // 获取视频详情
  const getVideoDetail = async () => {
    const [err, res] = await to(getVideoDetailApi(videoInfo.videoId));
    if (!err) {
      console.log(res);
      setVideoInfo((videoInfo: any) => {
        videoInfo = res.data;
        return videoInfo;
      });
    }
  };
  // 视频改变时调用
  useEffect(() => {
    // 清空上一个视频
    if (videoPlayer.current != "") {
      videoPlayer.current.dispose();
    }
    // 如果有用户信息就绑定id
    if (userInfo) {
      choseCollectionParams.current.userId = userInfo.userId;
    }
    videoPlay();
    getRelatedList();
    setCollectCount(videoInfo.collectionCount);
    setSupportCount(videoInfo.supportCount);
  }, [videoInfo]);
  // 挂载时调用
  useEffect(() => {
    getVideoDetail();
  }, []);

  // 记录上次一次播放时间
  const lastTime = useRef(0);
  //心跳包参数
  const heartBeatParams = useRef({
    videoId: "",
    currentTime: 0,
  });
  // 播放视频
  const videoPlay = async () => {
    const [err, res] = await to(getPlayAuthApi(videoInfo.videoId));
    if (!err) {
      videoPlayer.current = new Aliplayer(
        {
          id: "player-" + videoInfo.videoId,
          width: "100%",
          vid: res.data.vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
          playauth: res.data.playAuth, //必选参数。音视频播放凭证。
          autoplay: true,
          preload: true,
        },
        function (player) {
          console.log(userInfo, videoInfo);
          // 如果登录了
          if (userInfo) {
            // 制定时间开始播放
            player.seek(videoInfo.currentTime);
            // 绑定心跳包参数
            // heartBeatParams.current.userId = userInfo.userId;
            heartBeatParams.current.videoId = videoInfo.videoId;
            console.log(heartBeatParams.current);
            // 播放位置发生改变时触发，仅H5播放器。
            player.on("timeupdate", async () => {
              const time = player.getCurrentTime(); // 获取播放的时间
              if (Math.ceil(lastTime.current) === Math.ceil(time)) {
                // 相等则不发送请求
              } else {
                lastTime.current = time;
                if (
                  parseInt(`${time - videoInfo.currentTime}`) % 3 === 0 &&
                  parseInt(`${time - videoInfo.currentTime}`) != 0
                ) {
                  console.log("3秒了");
                  // 发送心跳包
                  heartBeatParams.current.currentTime = parseInt(`${time}`);
                  const [err, res] = await to(
                    heartBeatApi(heartBeatParams.current)
                  );
                  if (!err) {
                    console.log(res);
                  }
                }
              }
            });
          }
        }
      );
    }
  };

  // 切换播放/暂停状态
  const handleClickVideo = () => {
    // console.log(e.target);
    console.log(videoPlayer.current);
    if (videoPlayer.current.getStatus() === "pause") {
      videoPlayer.current.play();
    } else {
      videoPlayer.current.pause();
    }
  };

  // 获取热门视频列表
  const queryParams = useRef({
    videoId: "",
    status: "0",
    pageSize: 6,
    pageNum: 1,
    auditState: "0",
    orderByColumn: "createTime",
  });
  // 获取热门视频列表
  const getRelatedList = async () => {
    queryParams.current.videoId = videoInfo.videoId;
    const [err, res] = await to(getRelatedListApi(queryParams.current));
    if (!err) {
      setHotVideoList((hotVideoList: WebsiteVideoVo[]) => {
        hotVideoList = res.rows ?? [];
        console.log(hotVideoList);
        return hotVideoList;
      });
    }
  };
  // 视频播放按钮
  const handlePlay = (videoInfo: any) => {
    setVideoInfo(videoInfo);
    // 跳转页面并传递参数
    getRelatedList();
  };
  // 对视频点赞
  const handleLike = async () => {
    if (userInfo) {
      const [err] = await to(likeApi(videoInfo.videoId));
      if (!err) {
        if (!videoInfo.is_like) {
          setSupportCount(supportCount + 1);
          setVideoInfo((videoInfo) => {
            videoInfo.is_like = true;
            return videoInfo;
          });
          message.success("点赞成功");
        } else {
          setSupportCount(supportCount - 1);
          setVideoInfo((videoInfo) => {
            videoInfo.is_like = false;
            return videoInfo;
          });
          message.success("取消点赞成功");
        }
      } else {
        message.error("点赞失败");
      }
    } else {
      message.error("您还未登录，请先登录后操作!");
    }
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 获取收藏夹列表参数
  const getUserCollectParams = useRef({
    videoId: "",
    userId: "",
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    orderByColumn: "createTime",
  });
  const [collectList, setCollectList] = useState([]);
  // 获取收藏列表
  const getCollectList = async () => {
    getUserCollectParams.current.userId = userInfo.userId;
    getUserCollectParams.current.videoId = videoInfo.videoId;
    const [err, res] = await to(
      getCollectListApi(getUserCollectParams.current)
    );
    if (!err) {
      setCollectList(res.rows);
    }
  };
  // 收藏按钮
  const handleCollection = async () => {
    if (userInfo) {
      await getCollectList();
      setIsModalOpen(true);
    } else {
      message.error("您还未登录，请先登录后再操作");
    }
  };
  // 收藏视频参数
  const choseCollectionParams = useRef({
    targetId: "",
    userId: "",
    collectFolderId: "",
  });
  // 取消收藏参数
  const cancelChoseParams = useRef({
    videoId: "",
    collectFolderId: "",
  });
  // 选择收藏夹
  const handleChose = async (item: any) => {
    console.log(item);

    if (userInfo.userId) {
      // 如果已经登录
      choseCollectionParams.current.collectFolderId = item.collectFolderId;
      choseCollectionParams.current.targetId = videoInfo.videoId;
      const [err] = await to(choseCollectionApi(choseCollectionParams.current));
      if (!err) {
        setVideoInfo((videoInfo) => {
          videoInfo.is_collected = true;
          return videoInfo;
        });
        setCollectCount(collectCount + 1);
        await getCollectList();

        message.success("收藏成功");
      } else {
        message.success("收藏失败");
      }
    } else {
      message.success("您还未登录，请先登录后再操作");
    }
  };
  // 取消收藏按钮
  const handleCancelChose = async (item: any) => {
    cancelChoseParams.current.collectFolderId = item.collectFolderId;
    cancelChoseParams.current.videoId = videoInfo.videoId;
    const [err, res] = await to(
      handleCancelChoseApi(cancelChoseParams.current)
    );
    if (!err) {
      console.log(res);
      setCollectCount(collectCount - 1);

      message.success("取消成功");
      await getCollectList();
    }
  };
  // 取消选择收藏
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }

  const columns: ColumnsType<DataType> = [
    {
      title: "收藏夹名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          {record.is_collected && (
            <Button type="text" onClick={() => handleCancelChose(record)}>
              取消收藏
            </Button>
          )}
          {!record.is_collected && (
            <Button type="text" onClick={() => handleChose(record)}>
              选择
            </Button>
          )}
        </Space>
      ),
    },
  ];
  return (
    <>
      <div className="flex">
        <div style={{ width: "70%" }}>
          <div
            className="w100% h-50px mt-10px"
            style={{
              textAlign: "center",
              lineHeight: "50px",
              fontSize: "20px",
              fontWeight: "400",
            }}
          >
            {videoInfo.title}
          </div>
          <div style={{ margin: "0px 0 20px 67px", color: "rgb(161,166,172)" }}>
            <Flex justify={"flex-start"} align={"flex-start"}>
              <div>
                <YoutubeFilled />
                <span className="ml-5px">{videoInfo.clickCount}</span>
              </div>
              <div className="ml-25px">
                <MessageFilled />
                <span className="ml-5px">{videoInfo.commentCount}</span>
              </div>
              <div className="ml-25px">{videoInfo.createTime}</div>
              <div className="ml-25px">
                <span style={{ color: "red" }}>
                  <ExclamationOutlined />
                </span>
                <span className="ml-5px">未经作者授权，禁止转载</span>
              </div>
            </Flex>
          </div>

          <div
            id={"player-" + videoInfo.videoId}
            style={{ width: "800px", height: "500px", margin: "auto" }}
            onClick={handleClickVideo}
          ></div>
          <div className="flex ml-67px mt-10px mb-10px">
            <div>
              <Button
                onClick={handleLike}
                type="primary"
                shape="circle"
                icon={<HeartOutlined />}
                style={{ backgroundColor: videoInfo.is_like ? "#e5385c" : "" }}
              />
              {/* <HeartOutlined style={iconStyle} /> */}
              <span className="mr-80px">{supportCount}</span>
            </div>
            <div>
              <Button
                type="primary"
                shape="circle"
                onClick={handleCollection}
                icon={<StarOutlined />}
                style={{
                  backgroundColor: videoInfo.is_collected ? "#ffc921" : "",
                }}
              />

              {/* <StarOutlined style={iconStyle} /> */}
              {collectCount}
            </div>
          </div>

          <div>
            <hr className="w86%" />
          </div>

          <div className="w86% ml-67px">
            <Paragraph
              ellipsis={
                ellipsis ? { rows: 2, expandable: true, symbol: "更多" } : false
              }
            >
              {videoInfo.description}
            </Paragraph>
          </div>

          <div className="ml-67px mb-20px">
            <Flex wrap="wrap" gap="small">
              {videoInfo.tagList.map((item) => {
                return <Tag key={item.content}>{item.content}</Tag>;
              })}
            </Flex>
          </div>
          <div>
            <hr className="w86%" />
          </div>

          <div className="ml-67px mb-20px">
            <Flex gap="small">
              <h1>评论</h1>

              <h4
                style={{
                  height: "33px",
                  lineHeight: "33px",
                  marginLeft: "100px",
                }}
              >
                <Button type="text">最新</Button>
                <span style={{ margin: "0px 20px" }}>|</span>
                <Button type="text">最热</Button>
              </h4>
            </Flex>
          </div>
          {/* <div className="ml-67px mb-20px">
            <Flex gap="small">
              <Avatar size={64} icon={<UserOutlined />} />
              <Space.Compact style={{ width: "85%" }}>
                <Input
                  placeholder="请输入你想评论的内容"
                  onChange={(e) =>
                    (commentParams.commentContent = e.target.value)
                  }
                />
                <Button
                  className="h100%"
                  type="primary"
                  onClick={handleComment}
                >
                  提交
                </Button>
              </Space.Compact>
            </Flex>
          </div> */}
          <div className="ml-67px mb-20px">
            <Comment videoInfo={videoInfo}></Comment>
          </div>
        </div>
        <div style={{ width: "30%" }}>
          <Flex gap="small" className="mt-20px">
            <Avatar size={50} icon={<UserOutlined />} />
            <div className="mt-5px ml-10px">
              <div style={{ lineHeight: "100%" }}>userName</div>
              <div>个性签名。。。。</div>
              <Flex gap="small" className="mt-5px">
                <Button type="primary" size="small" icon={<EditOutlined />}>
                  发消息
                </Button>

                <Button type="primary" size="small" icon={<PlusOutlined />}>
                  关注
                </Button>
              </Flex>
            </div>
          </Flex>
          <div className="mt-20px">
            {hotVideoList.map((item: WebsiteVideoVo) => {
              return (
                <div
                  key={item.videoId}
                  onClick={() => handlePlay(item)}
                  className="cursor-pointer"
                >
                  <div
                    className="ml-20px w235px h145px mb-5px"
                    style={{ borderRadius: "2%", border: "1px solid #999" }}
                  >
                    {/* {(item.images ?? "" !== "") && ( */}
                    <img
                      src={item.images ?? ""}
                      // src="https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"
                      alt=""
                      className="absolute w-233px h-144px object-contain"
                      style={{ borderRadius: "3%" }}
                    />
                    {/* )} */}
                    <Tooltip title="开始播放">
                      <img
                        style={{
                          width: "40px",
                          height: "40px",
                          marginLeft: "100px",
                          marginTop: "54px",
                        }}
                        className="absolute  cursor-pointer"
                        src={"bigplay.png"}
                        alt=""
                      />
                    </Tooltip>
                  </div>
                  <Paragraph
                    ellipsis={{ rows: 1, expandable: false }}
                    className="ml-20px w240px h-20px"
                    style={{
                      lineHeight: "20px",
                      fontWeight: "600",
                      color: "#444",
                    }}
                  >
                    {item.title}
                  </Paragraph>
                  <div
                    className="ml-20px mt--10px mb-10px"
                    style={{ color: "#666", fontSize: "14px" }}
                  >
                    <span>
                      <UserOutlined />
                      {item.createBy}
                    </span>
                    <span className="ml-20px">{item.createTime}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      <Modal
        title="请选择收藏夹"
        open={isModalOpen}
        footer={[
          <Button key="submit" type="primary" onClick={handleCancel}>
            取消
          </Button>,
        ]}
      >
        <Table columns={columns} dataSource={collectList} />
      </Modal>
    </>
  );
};

// 评论组件
const Comment: React.FC = ({ videoInfo }) => {
  // 控制子列表评论展示
  const [childComment, setChildComment] = useState(false);
  // 控制子列表全部展示
  const [showAllComment, setShowAllComment] = useState(false);
  // 是否展示子评论的分页组件
  // 当前评论根节点id
  const [currentCommentId, setCurrentCommentId] = useState("");
  // 回复评论params
  const commentParams = useRef({
    content: "",
    targetId: "",
    parentId: "",
  });
  // 获取评论列表params
  const commentListParams = useRef({
    parentId: "",
    targetId: "",
    pageSize: 7,
    pageNum: 1,
    auditState: "0",
    orderByColumn: "createTime",
  });
  // 获取子评论列表params
  const childCommentListParams = useRef({
    parentId: "",
    targetId: "",
    pageSize: 4,
    pageNum: 1,
    auditState: "0",
    orderByColumn: "createTime",
  });
  const total = useRef(0);
  const childTotal = useRef(0);
  const userInfo = useSelector((state) => state.user);

  // 提交评论按钮
  const handleComment = async () => {
    console.log(userInfo);

    if (userInfo.userInfo) {
      commentParams.current.targetId = videoInfo.videoId;
      const [err] = await to(commentApi(commentParams.current));
      if (!err) {
        message.success("评论成功");
        await getCommentList();
      } else {
        message.error("评论失败");
      }
    } else {
      message.error("您还未登陆，请先登录后再评论！");
    }
  };
  // 子评论按钮
  const handleChildComment = (item: any) => {
    item.childComment = !item.childComment;
    setChildComment(!childComment);
    commentParams.current.parentId = item.id;
  };
  // 评论列表
  const [commentList, setCommentList] = useState([]);
  useEffect(() => {
    console.log("评论组件");
    getCommentList();
  }, [videoInfo.videoId]);
  useEffect(() => {
    // console.log("评论组件");
    // getCommentList();
  }, [commentList]);
  // 获取评论列表
  const getCommentList = async () => {
    commentListParams.current.targetId = videoInfo.videoId;
    const [err, res] = await to(getCommentListApi(commentListParams.current));
    if (!err) {
      console.log(res);
      total.current = res.total;
      console.log(total.current);

      setCommentList((commentList) => {
        commentList = res.rows;
        commentList.forEach((item: any) => {
          item.childComment = false;
          if (!item.children) {
            item.children = [];
          } else {
            item.children.forEach((item: any) => {
              item.childComment = false;
            });
          }
        });
        console.log(commentList);
        return commentList;
      });
    }
  };
  // 切换页码
  const onChange: PaginationProps["onChange"] = (pageNumber) => {
    commentListParams.current.pageNum = pageNumber;
    getCommentList();
  };
  // 切换子评论页面
  const childPageOnchange: PaginationProps["onChange"] = async (pageNumber) => {
    childCommentListParams.current.pageNum = pageNumber;
    // 获取子评论
    const [err, res] = await to(
      getChildCommentListApi(childCommentListParams.current)
    );
    if (!err) {
      setCommentList((commentList: any) => {
        // 修改引用对象，必须直接替换原对象！！！！
        const newCommentList = commentList.map((item) => {
          if (item.id === currentCommentId) {
            for (let i = 0; i < res.rows.length; i++) {
              item.children[i] = {};
              item.children[i].comment = res.rows[i];
            }
          }
          return item;
        });
        console.log(newCommentList);
        return newCommentList;
      });
      // setShowAllComment(true);
    }
  };

  // 查看所有评论
  const handleCheckAll = async (item: any) => {
    setCurrentCommentId(item.id);
    childCommentListParams.current.targetId = videoInfo.videoId;
    childCommentListParams.current.parentId = item.id;
    item.showPagination = true;
    item.children = [];
    const [err, res] = await to(
      getChildCommentListApi(childCommentListParams.current)
    );
    if (!err) {
      childTotal.current = res.total;
      for (let i = 0; i < res.rows.length; i++) {
        item.children[i] = {};
        item.children[i].comment = res.rows[i];
      }
      setShowAllComment(!showAllComment);
    }
  };
  return (
    <>
      <div className="ml-27px mb-20px">
        <Flex gap="small">
          <Avatar size={64} icon={<UserOutlined />} />
          <Space.Compact style={{ width: "85%" }}>
            <Input
              placeholder="请输入你想评论的内容"
              onChange={(e) => (commentParams.current.content = e.target.value)}
            />
            <Button className="h100%" type="primary" onClick={handleComment}>
              提交
            </Button>
          </Space.Compact>
        </Flex>
      </div>
      <div>
        {commentList.map((item: any) => {
          return (
            <>
              <div
                className="m-20px p-10px"
                style={{ borderBottom: "1px solid rgb(136,138,143)" }}
              >
                <Flex gap="small">
                  <Avatar size={45} icon={<UserOutlined />} />
                  <div className="ml-20px">
                    <div style={{ fontSize: "13px" }}>
                      {item.comment.nickName}
                    </div>
                    <div style={{ fontSize: "15px", margin: "10px 0" }}>
                      {item.comment.content}
                    </div>
                    <Flex gap="small" style={{ color: "#888" }}>
                      <div>{item.comment.createTime}</div>
                      <div className="ml-20px mt--5px">
                        <Button
                          size="small"
                          shape="circle"
                          icon={<LikeOutlined />}
                        />

                        <Button
                          style={{ borderStyle: "none" }}
                          className="ml-10px"
                          size="small"
                          shape="circle"
                          icon={<DislikeOutlined />}
                        />
                        <Button
                          style={{ borderStyle: "none" }}
                          className="ml-10px"
                          size="small"
                          type="text"
                          onClick={() => handleChildComment(item)}
                        >
                          回复
                        </Button>
                      </div>
                    </Flex>
                    {/* 子评论列表 */}
                    {item.children.map((subItem: any) => {
                      return (
                        <>
                          <Flex
                            gap="small"
                            style={{
                              marginTop: "20px",
                            }}
                          >
                            <Avatar size={35} icon={<UserOutlined />} />
                            <div className="ml-20px">
                              <div style={{ fontSize: "13px" }}>
                                {subItem.comment.nickName}
                              </div>
                              <div
                                style={{ fontSize: "15px", margin: "10px 0" }}
                              >
                                {subItem.comment.content}
                              </div>
                              <Flex gap="small" style={{ color: "#888" }}>
                                <div>{subItem.comment.createTime}</div>
                                <div className="ml-20px mt--5px">
                                  <Button
                                    size="small"
                                    shape="circle"
                                    icon={<LikeOutlined />}
                                  />

                                  <Button
                                    style={{ borderStyle: "none" }}
                                    className="ml-10px"
                                    size="small"
                                    shape="circle"
                                    icon={<DislikeOutlined />}
                                  />
                                  <Button
                                    style={{ borderStyle: "none" }}
                                    className="ml-10px"
                                    size="small"
                                    type="text"
                                    onClick={() => handleChildComment(subItem)}
                                  >
                                    回复
                                  </Button>
                                </div>
                              </Flex>
                            </div>
                          </Flex>

                          <Flex
                            gap="small"
                            className="mt-20px"
                            style={{
                              display: subItem.childComment ? "" : "none",
                            }}
                          >
                            <Avatar size={35} icon={<UserOutlined />} />
                            <Space.Compact style={{ width: "85%" }}>
                              <Input
                                placeholder="请输入你想评论的内容"
                                onChange={(e) =>
                                  (commentParams.current.content =
                                    e.target.value)
                                }
                              />
                              <Button
                                className="h100%"
                                type="primary"
                                onClick={handleComment}
                              >
                                提交
                              </Button>
                            </Space.Compact>
                          </Flex>
                        </>
                      );
                    })}

                    {item.showPagination && (
                      <Pagination
                        showQuickJumper
                        defaultCurrent={1}
                        total={childTotal.current}
                        onChange={childPageOnchange}
                      />
                    )}

                    <div
                      className="ml-70px"
                      style={{
                        color: "#999",
                        display: item.children.length === 2 ? "" : "none",
                      }}
                    >
                      <span>共{item.children.length}条评论</span>
                      <Button
                        type="text"
                        style={{ color: "#999" }}
                        onClick={() => handleCheckAll(item)}
                      >
                        查看所有
                      </Button>
                    </div>
                  </div>
                </Flex>

                <Flex
                  gap="small"
                  className="mt-20px"
                  style={{ display: item.childComment ? "" : "none" }}
                >
                  <Avatar size={50} icon={<UserOutlined />} />
                  <Space.Compact style={{ width: "85%" }}>
                    <Input
                      placeholder="请输入你想评论的内容"
                      onChange={(e) =>
                        (commentParams.current.content = e.target.value)
                      }
                    />
                    <Button
                      className="h100%"
                      type="primary"
                      onClick={handleComment}
                    >
                      提交
                    </Button>
                  </Space.Compact>
                </Flex>
              </div>
            </>
          );
        })}
      </div>
      {total.current > 0 && (
        <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={total.current}
          onChange={onChange}
        />
      )}
    </>
  );
};

export default Index;
